package com.huawei.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.huawei.common.BaseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义退出成功处理器
 */
@Component
public class AppLogoutSuccessHandler implements LogoutSuccessHandler {
    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
                                Authentication authentication) throws IOException, ServletException {
        // 处理post请求中文乱码问题
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 构建JSON需要的对象数据
        BaseResult result = new BaseResult();

        // 删除redis中存放的token
        // 获取请求头中的token
        String jwtToken = request.getHeader("token");

        // 检查token是否为空
        if (jwtToken == null) {
            // 如果token为空，返回错误信息
            BaseResult rs = new BaseResult(-1, "token不能为空");
            response.getWriter().write(objectMapper.writeValueAsString(rs));
            return;
        }

        // 删除redis中的token
        stringRedisTemplate.delete("token:" + jwtToken);

        // 将封装好的数据转为JSON并返回
        result.setMessage("恭喜您,退出成功");
        response.getWriter().write(objectMapper.writeValueAsString(result));
    }


}
